<!--听书页轮播和听书分类推荐-->
<template>
  <el-dialog
    :title="popup.title"
    :close-on-click-modal="false"
    :style="{'min-width':adjustWidth}"
    :visible.sync="visible">
    <el-form :model="appConf" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="配置名称" prop="name">
        <el-input v-model="appConf.name" placeholder="请输入轮播配置名称（如：春节用）" style="width: 300px;"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="排布模式" prop="stretchMode " v-if="popup.confType=='recommend'">
        <el-select style="width: 120px;"
                   v-model="appConf.stretchMode"
                   placeholder="请选择">
          <el-option
            v-for="(option,index) in stretchModeOptions"
            :key="index"
            :label="option.label"
            :value="option.value">
          </el-option>
        </el-select>
      </el-form-item>
      <div style="display: flex;">
        <div style="margin-top: 20px;width: 80px;">
          <span style="color: #f56c6c;margin-right: 4px">*</span>轮播内容
        </div>
        <div>
          <div v-for="(item,index) in itemList" style="margin-top: 10px;" :key="index"
               v-dragging="{ item: item, list: itemList, group: 'item' }">
            <div class="move-tip-icon">&lt;&gt;</div>
            <el-checkbox style="margin-right: 20px;" size="mini" v-model="item.checkedUrl"
                         v-if="isUploadUrl">
              页面链接
            </el-checkbox>
            <template v-if="!item.checkedUrl">
              <el-autocomplete
                style="width: 200px;"
                v-model="itemList[index].selectedItem.nameCode"
                clearable
                :hide-loading="true"
                :fetch-suggestions="querySearch"
                placeholder="请输入音频ID或者音频名称"
                :trigger-on-focus="false"
                @select="handleSelect"
                @focus="getFocusInput(item,index)">
                <template slot-scope="{ item }">
                  <div>{{ item.name }}</div>
                </template>
              </el-autocomplete>
              <!--<el-select v-model="item.selectedSubItem.id" v-if="item.subItems&&item.subItems.length>0">-->
                <el-select v-model="item.selectedSubItem.id" v-if="false">
                <el-option
                  v-for="subItem in item.subItems"
                  :key="subItem.id"
                  :label="subItem.itemName"
                  :value="subItem.id">
                </el-option>
              </el-select>
            </template>
            <template v-else>
              <el-input v-model="item.url" placeholder="请输入url或者ios内部路由" style="width: 200px;" clearable></el-input>
              <el-input v-model="item.hiosUrl" placeholder="安卓内部路由hiosUrl" style="width: 200px;" clearable></el-input>
              <el-tooltip effect="dark" :content="item.urlBannerImg?item.urlBannerImg:'请上传页面封面图'" placement="top-start">
                <el-input v-model="item.urlBannerImg" placeholder="请上传页面封面图" disabled style="width: 200px;"></el-input>
              </el-tooltip>
              <el-upload
                style="display: inline-block;"
                ref="uploadBannerImg"
                :action="uploadBannerImgUrl"
                :before-upload="beforeBannerImgUpload"
                :on-error="handleBannerImgError"
                :on-success="handleBannerImgSuccess"
                :show-file-list="false">
                <el-button type="primary" style="margin:0 10px;" @click="getUploadTag(item,index)" size="mini">上传
                </el-button>
              </el-upload>
            </template>
            <el-button type="danger" icon="el-icon-delete" circle @click="deleteItem(index)"
                       :style="{'margin-left':(item.subItems&&item.subItems.length>0)?'0px':'0px'}"></el-button>
          </div>
        </div>
      </div>
      <el-form-item>
        <el-button type="primary" @click="addList" style="margin-top: 20px;">新增一项</el-button>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    <div style="margin-left: 80px;color:#f56c6c;" v-if="showErrorTip">
      <i class="el-icon-warning" style="color: red;margin-right: 10px;"></i>还有信息未填完整，请检查！
    </div>
    <div style="margin-left: 80px;" v-if="popup.attentionTip">
      <i class="el-icon-warning" style="color: red;margin-right: 10px;"></i>{{popup.attentionTip}}
    </div>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        stretchModeOptions: [{label: '大小', value: 12},  {label: '小小', value: 22}],
        uploadBannerImgUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),
        uploadItem: {},
        uploadItemIndex: 0,
        // attentionTip: '',
        selectedInputItemIndex: 0,
        id: '',
        showErrorTip: false,
        mediaConfs: [],
        itemList: [],
        popup: {},
        appConf: {
          id: '',
          confType: '',
          confSecondType: '',
          name: '',
          stretchMode: 22
        },
        dataRule: {
          name: [
            {required: true, message: '配置名称不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    computed: {
      adjustWidth () {
        if (this.itemList.length > 0) {
          for (var i = 0; i < this.itemList.length; i++) {
            if (this.itemList[i].checkedUrl) {
              return '2000px'
            }
          }
        }
        return '1600px'
      }
    },
    methods: {
      init (id, popup) {
        let _this = this
        _this.popup = Object.assign({}, popup)
        _this.showErrorTip = false
        _this.id = id || 0
        _this.visible = true
        _this.isUploadUrl = popup.isUploadUrl || false
        _this.uploadItem = {}
        _this.uploadItemIndex = 0
        _this.appConf.confType = popup.confType
        _this.appConf.confSecondType = popup.confSecondType
        _this.appConf.name = ''
        _this.appConf.stretchMode = 22
        _this.itemList = [{
          checkedUrl: false,
          url: '',
          hiosUrl: '',
          urlBannerImg: '',
          selectedItem: {//选中的音频
            'id': '',
            'nameCode': '',
          },
          selectedSubItem: {//选中的音频子项
            'id': '',
            'itemName': '',
          },
          subItems: []//当前音频的所有子项
        }]
        _this.$nextTick(() => {
          _this.$refs['dataForm'].resetFields()
          if (_this.id) {
            _this.$http({
              url: _this.$http.adornUrl(`/picbook/appconf/v2/info/media/${_this.id}`),
              method: 'post',
              params: _this.$http.adornParams({id: _this.id})
            }).then(({data}) => {
              if (data && data.code === 0 && data.data && data.data.mediaConfs && data.data.mediaConfs.length > 0) {
                _this.appConf = data.data.appConf
                _this.itemList = []
                data.data.mediaConfs.forEach(function (item) {
                  _this.itemList.push({
                    checkedUrl: item.sourceType === 'url',
                    url: item.url,
                    hiosUrl: item.hiosUrl,
                    urlBannerImg: item.urlBannerImg,
                    selectedItem: {//选中的音频
                      'id': item.pid,
                      'nameCode': item.nameCode,
                    },
                    selectedSubItem: {//选中的音频子项
                      'id': item.itemId,
                      'itemName': item.itemName,
                    },
                    subItems: item.itemList//当前音频的所有子项
                  })
                })
              }
            })
          }
        })
      },

      // 表单提交
      dataFormSubmit () {
        let _this = this
        _this.showErrorTip = false
        _this.itemList.map(function (value) {
          if (_this.isUploadUrl && value.checkedUrl) {
            if (!value.urlBannerImg || !value.url) {
              _this.showErrorTip = true
              return
            }
          } else {
            if (!value.selectedItem.id) {
              _this.showErrorTip = true
              return
            }
          }

        })
        if (_this.isUploadUrl && _this.itemList.length < 3) {
          _this.showErrorTip = true
          return
        }
        _this.$refs['dataForm'].validate((valid) => {
          if (valid && !_this.showErrorTip) {
            var mediaConfs = []
            _this.itemList.map(function (value, index, array) {
              var mediaConf = {}
              if (_this.isUploadUrl && value.checkedUrl) {//上传页面链接
                mediaConf.sourceType = 'url'
                mediaConf.url = value.url
                mediaConf.hiosUrl = value.hiosUrl
                mediaConf.urlBannerImg = value.urlBannerImg
              } else {//上传音频
                mediaConf = {pid: value.selectedItem.id, sourceType: 'audio'}
                if (value.selectedSubItem.id) {
                  mediaConf.itemId = value.selectedSubItem.id
                }
              }
              mediaConfs.push(mediaConf)
            })
            let url = _this.id ? '/picbook/appconf/v2/update' : ('/picbook/appconf/v2/save/audio/' + _this.popup.confType)
            _this.$http({
              url: _this.$http.adornUrl(url),
              method: 'post',
              data: _this.$http.adornData({
                appConf: _this.appConf,
                mediaConfs: mediaConfs
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                _this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 500,
                  onClose: () => {
                    _this.visible = false
                    _this.$emit('refreshDataList')
                  }
                })
              } else {
                _this.$message.error(data.msg)
              }
            })
          }
        })
      },
      addList () {
        if (!this.appConf.confType) {
          return
        }
        var maxCount = this.popup.maxCount || 6
        if (!this.popup.maxCount || this.itemList.length < maxCount) {
          this.itemList.push({
            checkedUrl: false,
            url: '',
            hiosUrl: '',
            urlBannerImg: '',
            selectedItem: {//选中的音频
              'id': '',
              'nameCode': '',
            },
            selectedSubItem: {//选中的音频子项
              'id': '',
              'itemName': '',
            },
            subItems: []//当前音频的所有子项
          })
        } else {
          this.popup.maxAddTip && this.$message.warning(this.popup.maxAddTip)
        }
      },
      deleteItem (index) {
        if (this.itemList.length > index && this.itemList.length > 1) {
          this.itemList.splice(index, 1)
        } else if (index == 0 && this.itemList.length == 1) {
          this.itemList = [{
            checkedUrl: false,
            url: '',
            hiosUrl: '',
            urlBannerImg: '',
            selectedItem: {//选中的音频
              'id': '',
              'nameCode': '',
            },
            selectedSubItem: {//选中的音频子项
              'id': '',
              'itemName': '',
            },
            subItems: []//当前音频的所有子项
          }]
        }
      },
      getFocusInput (item, index) {
        this.selectedInputItemIndex = index
      },
      querySearch (queryString, cb) {
        this.$http({
          url: this.$http.adornUrl('/picbook/combobox/v2/listSimpleMedia/audio'),
          method: 'post',
          data: this.$http.adornData({
            'text': queryString
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            cb(data.data)
          } else {
            cb([])
          }
        }).catch(() => {
          cb([])
        })
      },
      handleSelect (item) {
        var _this = this
        _this.itemList[_this.selectedInputItemIndex].selectedItem = item
        //查询音频子项
        _this.$http({
          url: _this.$http.adornUrl(`/picbook/combobox/v2/listAudioItem/` + item.id),
          method: 'post',
          data: _this.$http.adornData({
            'id': item.id
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            _this.itemList[_this.selectedInputItemIndex].subItems = data.data
          }
        })
      },
      getUploadTag (item, index) {
        this.uploadItem = item
        this.uploadItemIndex = index
      },
      handleBannerImgSuccess (res, file) {
        this.uploadItem.urlBannerImg = res.url
        this.itemList[this.uploadItemIndex].urlBannerImg = res.url
        // debugger
        // let _this = this
        // setTimeout(function () {
        //   _this.$refs.uploadBannerImg.clearFiles()
        // }, 1000)
      },
      beforeBannerImgUpload (file) {
        if (file.type.indexOf('image') < 0) {
          this.$message.error('图片格式不正确')
          return false
        }
      },
      handleBannerImgError (err, file, fileList) {
        this.$message.error('上传失败')
      },
    }
  }
</script>
<style lang="less" scoped>
  .move-tip-icon {
    display: inline-block;
    font-size: 18px;
    font-weight: 400;
    transform: rotate(90deg);
    -ms-transform: rotate(90deg); /* IE 9 */
    -moz-transform: rotate(90deg); /* Firefox */
    -webkit-transform: rotate(90deg); /* Safari 和 Chrome */
    -o-transform: rotate(90deg); /* Opera */
  }
</style>
